package top.dark.ware.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import top.dark.common.constant.WareConstant;
import top.dark.common.utils.PageUtils;
import top.dark.common.utils.Query;

import top.dark.ware.dao.PurchaseDao;
import top.dark.ware.entity.PurchaseDetailEntity;
import top.dark.ware.entity.PurchaseEntity;
import top.dark.ware.entity.WareSkuEntity;
import top.dark.ware.service.PurchaseDetailService;
import top.dark.ware.service.PurchaseService;
import top.dark.ware.service.WareOrderTaskDetailService;
import top.dark.ware.service.WareSkuService;
import top.dark.ware.vo.DonePurchaseDetailVo;
import top.dark.ware.vo.DonePurchaseVo;
import top.dark.ware.vo.MergePurchaseVo;

import javax.xml.crypto.Data;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils unreceiveList(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", WareConstant.PurchaseStatusEnum.CREATED.getCode())
                        .or().eq("status", WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()));
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergePurchaseVo mergePurchaseVo) {
        Long purchaseId = mergePurchaseVo.getPurchaseId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        if (purchaseId == null) {
            // 表示创建一个新的采购单
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setPriority(0);
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        } else {// 表示采购单已存在
            // todo 先检验采购单的状态
            PurchaseEntity entity = this.getById(purchaseId);
            if (entity.getStatus() != WareConstant.PurchaseStatusEnum.CREATED.getCode() &&
                    entity.getStatus() != WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return;
            }
        }

        // 更新采购项状态信息
        Long[] itemIds = mergePurchaseVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> entityList = Arrays.stream(itemIds).filter(id -> {
            PurchaseDetailEntity entity = purchaseDetailService.getById(id);
            if (entity.getStatus() == WareConstant.PurchaseDetialStatusEnum.CREATED.getCode() ||
                    entity.getStatus() == WareConstant.PurchaseDetialStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(id -> {
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            entity.setId(id);
            entity.setPurchaseId(finalPurchaseId);
            entity.setStatus(WareConstant.PurchaseDetialStatusEnum.ASSIGNED.getCode());
            return entity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(entityList);
    }

    @Override
    public void receivedPurchase(List<Long> purchaseIds) {
        List<PurchaseEntity> purchaseEntities = purchaseIds.stream().filter(id -> {
            // 确认当前采购单是新建状态或者已分配状态
            PurchaseEntity entity = this.getById(id);
            if (entity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    entity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(id -> {
            // 更新采购单状态
            PurchaseEntity entity = new PurchaseEntity();
            entity.setId(id);
            entity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            entity.setUpdateTime(new Date());
            return entity;
        }).collect(Collectors.toList());
        this.updateBatchById(purchaseEntities);

        // 更新采购项状态
        purchaseIds.forEach(purchaseId ->{
            List<PurchaseDetailEntity> entityList = purchaseDetailService.listDetailByPurchaseId(purchaseId);
            List<PurchaseDetailEntity> purchaseDetailEntities = entityList.stream().map(item -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setId(item.getId());
                entity.setStatus(WareConstant.PurchaseDetialStatusEnum.BUYING.getCode());
                return entity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailEntities);
        });
    }

    @Transactional
    @Override
    public void done(DonePurchaseVo donePurchaseVo) {
        // 更新采购项状态
        Boolean flag = true;
        List<DonePurchaseDetailVo> items = donePurchaseVo.getItems();
        List<PurchaseDetailEntity> detailEntities = new ArrayList<>();
        for (DonePurchaseDetailVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetialStatusEnum.HASERROR.getCode()) {
                flag = false;
            } else {
                // 将采购成功的数据进行入库
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());
            purchaseDetailEntity.setStatus(item.getStatus());
            detailEntities.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(detailEntities);

        // 更新采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(donePurchaseVo.getId());
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        this.updateById(purchaseEntity);
    }


}